/**
 * 
 */
package fhq.hcmute.modernshopping.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import fhq.hcmute.modernshopping.R;

/**
 * @author: Hien Nguyen Le
 * @emai: hien.nguyenle.it@gmail.com
 * 
 */
public class Webservice extends AsyncTask<String, Void, String> {

	public static final int GET_DATA_SUCCESSFUL = 0;
	public static final int GET_DATA_FAILED = -1;
	private ProgressDialog progressDialog;
	private Context context;
	private Handler handler;

	public Webservice(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		
	}

	@Override
	protected String doInBackground(String... params) {
		return readJSONFeed(params[0]);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage(context
				.getString(R.string.progress_bar_title_waiting));
		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
	}

	@Override
	protected void onPostExecute(String result) {
		progressDialog.dismiss();
		Message message = this.handler.obtainMessage(GET_DATA_SUCCESSFUL,
				result);
		handler.sendMessage(message);
		super.onPostExecute(result);
	}

	public String readJSONFeed(String URL) {
		StringBuilder stringBuilder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(URL);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					stringBuilder.append(line);
				}
			} else {
				Message message = this.handler.obtainMessage(GET_DATA_FAILED);
				handler.sendMessage(message);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}
}
